#!/usr/bin/python
# -*- coding: utf-8 -*-
from aijia.utils.wx_sdk import wx_sdk
from django.contrib.auth import login,logout
from django.views import View
from django.http import *
import json,re,logging
from django_redis import get_redis_connection
from django.contrib.auth import authenticate
from fdfs_client.client import Fdfs_client
from django.conf import settings

from aijia.utils.response_code import RETCODE
from users.models import User
from aijia.utils.views import LoginRequiredJSONMixin

logger = logging.getLogger('django')


class Regisiter(View):  # drf用着不方便
    '''用户注册'''
    def post(self,request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        phonecode = json_dict.get('phonecode')
        password = json_dict.get('password')
        # 校验参数
        if not all([mobile,phonecode,password]):
            return HttpResponseForbidden({
                'errno':RETCODE.PARAMERR,
                'errmsg':'缺少参数'
            })
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden({
                'errno': RETCODE.PARAMERR,
                'errmsg': '请输入正确手机号'
            })
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden({
                'errno': RETCODE.PARAMERR,
                'errmsg': '请输入正确密码'
            })
        redis_conn = get_redis_connection('verify_code')
        sms_code = redis_conn.get('mobile_%s' % mobile)
        # 判断验证码是否过期
        if sms_code is None:
            return HttpResponseNotFound({
                'errno':RETCODE.DBERR,
                'errmsg':'验证码过期'
            })
        # 删除验证码
        try:
            redis_conn.delete('mobile_%s' % mobile)
        except Exception as e:
            logger.error(e)
        # 将查询出的bty数据转为字符串
        sms_code = sms_code.decode()
        if sms_code != phonecode:
            return HttpResponseForbidden({
                'errno':RETCODE.DATAERR,
                'errmsg':'验证码错误'
            })
        # 新建用户
        user = User.objects.create_user(username=mobile,mobile=mobile,password=password)
        # 状态保持
        login(request,user)
        # 响应参数
        return JsonResponse({
            'errno':RETCODE.OK,
            'errmsg':'注册成功'
        })


class Login(View):
    '''用户登录'''
    def post(self,request):

        # 接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        # 校验参数
        if not all([mobile,password]):
            return HttpResponseForbidden({
                'errno':RETCODE.PARAMERR,
                'errmsg':'缺少参数'
            })
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden({
                'errno': RETCODE.PARAMERR,
                'errmsg': '请输入正确手机号'
            })
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden({
                'errno': RETCODE.PARAMERR,
                'errmsg': '请输入正确密码'
            })
        # 用户认证
        # 查询用户名
        try:
            username = User.objects.get(mobile=mobile).username
        except :
            return JsonResponse({
                'errno':RETCODE.PARAMERR,
                'errmsg':'该手机号不存在'
            })

        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({
                'errno':RETCODE.PARAMERR,
                'errmsg':'密码错误'
            })
        # 状态保持
        login(request,user)
        # 返回响应
        return JsonResponse({
            'errno':RETCODE.OK,
            'errmsg':'登录成功'
        })

    def get(self,request):

        # 判断用户是否登录
        user = request.user.is_authenticated()
        if not user:
            return JsonResponse({
                'errno':RETCODE.SESSIONERR,
                'errmsg':'用户未登录'
            })
        return JsonResponse({
            'errno':RETCODE.OK,
            'errmsg':'已登录',
            'data':{
                'user_id':request.user.id,
                'name':request.user.username
            }
        })

    def delete(self,request):

        # 退出登录
        logout(request)
        return JsonResponse({
            'errno':RETCODE.OK,
            'errmsg':'已登出'
        })


class UserInfoView(LoginRequiredJSONMixin, View):
    """
        用户中心
    """

    def get(self, request):
        """
            获取用户中心信息
        :param request:
        :return:
        """
        # 构造响应数据
        data = {
            "avatar_url": request.user.avatar.url,
            # "avatar": None,
            "create_time": request.user.date_joined,
            "mobile": request.user.mobile,
            "name": request.user.username,
            "user_id": request.user.id
        }

        # 响应结果
        return JsonResponse(
            {
                'data': data,
                'errmsg': 'ok',
                'errno': '0',
            }
        )


class UpdateUsernameView(LoginRequiredJSONMixin, View):
    """
        修改用户名
    """

    def put(self, request):
        """修改用户名"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('name')

        # 校验用户名是否合法
        if not re.match(r'^[a-zA-Z0-9_-]{5,15}$', username):
            return JsonResponse({'errno': '1', 'errmsg': '请输入正确的用户名'})

        try:

            request.user.username = username
            request.user.save()
        except Exception as e:
            return JsonResponse({'errno': '1', 'errmsg': '用户名修改失败'})
        else:
            return JsonResponse({'errno': '0', 'errmsg': '修改成功'})


class UploadUseravatarView(LoginRequiredJSONMixin, View):
    """
        上传用户头像
    """
    def post(self, request):
        # 创建FastDFS客户端
        client = Fdfs_client(settings.PASTDFS_PATH)

        # 获取要上传的图片对象
        file = request.FILES.get('avatar')
        # 上传图片二进制信息
        res = client.upload_by_buffer(file.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return JsonResponse({'errno': '1', 'errmsg': '个人头像上传失败'})

        # 将用户头像信息保存到数据库
        request.user.avatar = res['Remote file_id']
        request.user.save()

        # 构建响应数据
        data = {
            'avatar_url': request.user.avatar.url
        }
        # 响应结果
        return JsonResponse({'data': data, 'errno': '0', 'errmsg': '头像上传成功'})


class UserAuthView(LoginRequiredJSONMixin, View):
    """
        用户身份认证
    """
    def get(self, request):
        """判断用户是否认证"""
        real_name = request.user.real_name
        id_card = request.user.id_card
        if real_name and id_card:
            # 构造数据
            data = {
                'real_name': real_name,
                'id_card': id_card
            }
            return JsonResponse({"data": data, "errno": "0", "errmsg": "已经实名认证"})

    def post(self, request):
        """用户的实名认证"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')

        # 第三方平台进行实名认证
        # 京东云的接口地址
        url = settings.WX_SDK_URL
        # 查询参数
        params = {
            'identityNo': id_card,
            'name': real_name,
            'appkey': '8ea3de14626c909d5ab18f7b38b357ee'
        }
        # 进行实名认证
        response = wx_sdk.wx_post_req(url, params)
        print(response.text)
        # 将返回的信息由字符串转换为json字典
        json_dict1 = json.loads(response.text)
        # 获取认证结果的状态码
        result = json_dict1.get('result')
        data = result.get('data')
        resultCode = data.get('resultCode')
        # 判断认证结果
        if resultCode == 'R001':
            # 表示用户实名认证成功
            # 将用户的真实名和身份证号保存到数据库中，和用户进行绑定
            request.user.real_name = real_name
            request.user.id_card = id_card
            request.user.save()
        else:
            # 用户实名认证失败
            return JsonResponse({"errno": "1", "errmsg": "实名认证失败"})

        # 响应结果
        return JsonResponse({ "errno": "0", "errmsg": "认证信息保存成功"})






